package com.liuyi.tools;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName SpringContext
 * @Description TODO SpringContext 类
 * @createTime 2019/9/16 10:59
 */
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext get() {
        if (applicationContext == null) throw new IllegalArgumentException("applicationContext 未注入");
        return applicationContext;
    }

    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();
        return applicationContext.getBean(requiredType);
    }

    public static <T> T getNullToBean(Class<T> requiredType) {
        assertApplicationContext();
        try {
            return applicationContext.getBean(requiredType);
        } catch (BeansException e) {
            return null;
        }
    }

    public static Environment getEnv(){
        return getBean(Environment.class);
    }

    private static void assertApplicationContext() {
        if (applicationContext == null) {
            throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
        }
    }
}
